package com.logistics.baiqun.bugly;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.util.Log;
import android.widget.Toast;

import com.joanzapata.iconify.fonts.FontAwesomeModule;
import com.logistics.baiqun.R;
import com.orhanobut.logger.AndroidLogAdapter;
import com.shadow.baiqun.config.ServiceUrl;
import com.shadow.baiqun.icon.FontEcModule;
import com.shadow.core.app.Shadow;
import com.shadow.core.net.interceptors.AddCookieInterceptor;
import com.shadow.core.net.interceptors.GetCookieInterceptor;
import com.shadow.core.net.interceptors.LoggingInterceptor;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.interfaces.BetaPatchListener;
import com.tencent.bugly.beta.upgrade.UpgradeStateListener;
import com.tencent.tinker.loader.app.DefaultApplicationLike;

import java.util.Locale;

/**
 * @author zhangyu
 * @date 2018/3/13
 */

public class MyApplication extends DefaultApplicationLike {
    private static final String TAG = "MyApplication";
    private static final String APP_ID = "3d976deba2";

    public MyApplication(Application application,
                         int tinkerFlags,
                         boolean tinkerLoadVerifyFlag,
                         long applicationStartElapsedTime,
                         long applicationStartMillisTime,
                         Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag,
                applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }

    @SuppressWarnings("DanglingJavadoc")
    @Override
    public void onCreate() {
        super.onCreate();
        /**
         * true表示app启动自动初始化升级模块；.
         * false不好自动初始化
         * 开发者如果担心sdk初始化影响app启动速度，可以设置为false
         * 在后面某个时刻手动调用
         */
        Beta.autoInit = true;
        /**
         * true表示初始化时自动检查升级.
         * false表示不会自动检查升级，需要手动调用Beta.checkUpgrade()方法
         */
        Beta.autoCheckUpgrade = true;
        /**
         * 设置升级周期为60s（默认检查周期为0s），60s内SDK不重复向后天请求策略.
         */
        Beta.initDelay = 1000;

        /**
         * 设置通知栏大图标，largeIconId为项目中的图片资源；.
         */
        Beta.largeIconId = R.mipmap.ic_launcher;
        /**
         * 设置状态栏小图标，smallIconId为项目中的图片资源id;.
         */
        Beta.smallIconId = R.mipmap.ic_launcher;
        /**
         * 设置更新弹窗默认展示的banner，defaultBannerId为项目中的图片资源Id;.
         * 当后台配置的banner拉取失败时显示此banner，默认不设置则展示“loading“;
         */
        Beta.defaultBannerId = R.mipmap.ic_launcher;
        /**
         * 设置sd卡的Download为更新资源保存目录;.
         * 后续更新资源会保存在此目录，需要在manifest中添加WRITE_EXTERNAL_STORAGE权限;
         */
        Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        /**
         * 点击过确认的弹窗在APP下次启动自动检查更新时会再次显示;.
         */
        Beta.showInterruptedStrategy = true;
        /**
         *  设置自定义升级对话框UI布局.
         *  注意：因为要保持接口统一，需要用户在指定控件按照以下方式设置tag，否则会影响您的正常使用：
         *  标题：beta_title，如：android:tag="beta_title"
         *  升级信息：beta_upgrade_info  如： android:tag="beta_upgrade_info"
         *  更新属性：beta_upgrade_feature 如： android:tag="beta_upgrade_feature"
         *  取消按钮：beta_cancel_button 如：android:tag="beta_cancel_button"
         *  确定按钮：beta_confirm_button 如：android:tag="beta_confirm_button"
         *  详见layout/upgrade_dialog.xml
         */
        Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog;
        /**
         * 设置自定义tip弹窗UI布局.
         * 注意：因为要保持接口统一，需要用户在指定控件按照以下方式设置tag，否则会影响您的正常使用：
         *  标题：beta_title，如：android:tag="beta_title"
         *  提示信息：beta_tip_message 如： android:tag="beta_tip_message"
         *  取消按钮：beta_cancel_button 如：android:tag="beta_cancel_button"
         *  确定按钮：beta_confirm_button 如：android:tag="beta_confirm_button"
         *  详见layout/tips_dialog.xml
         */
        Beta.tipsDialogLayoutId = R.layout.tips_dialog;
        /**
         *  设置更新状态回调接口
         *  */
        Beta.upgradeStateListener = new UpgradeStateListener() {
            @Override
            public void onUpgradeSuccess(boolean isManual) {
                //Toast.makeText(getApplicationContext(),"UPGRADE_SUCCESS",Toast.LENGTH_SHORT).show();
                Log.i(TAG, "更新成功");
            }

            @Override
            public void onUpgradeFailed(boolean isManual) {
                //                Toast.makeText(getApplicationContext(),"UPGRADE_FAILED",Toast.LENGTH_SHORT).show();
                Log.i(TAG, "更新失败");
            }

            @Override
            public void onUpgrading(boolean isManual) {
                //                Toast.makeText(getApplicationContext(),"UPGRADE_CHECKING",Toast.LENGTH_SHORT).show();
                Log.i(TAG, "检查更新");
            }

            @Override
            public void onDownloadCompleted(boolean b) {
                //                Toast.makeText(getApplicationContext(),"onDownloadCompleted",Toast.LENGTH_SHORT).show();
                Log.i(TAG, "下载完成");

            }

            @Override
            public void onUpgradeNoVersion(boolean isManual) {
                //                Toast.makeText(getApplicationContext(),"UPGRADE_NO_VERSION",Toast.LENGTH_SHORT).show();
                Log.i(TAG, "更新未检测到新版本");
            }
        };
        /**
         * wifi下自动下载
         */
        Beta.autoDownloadOnWifi = true;
        /**
         * 是否显示弹窗apk信息（默认弹窗）
         */
        Beta.canShowApkInfo = true;
        /**
         * 设置是否开启热更新能力，默认为true
         */
        Beta.enableHotfix = true;
        /**
         * 设置是否自动下载补丁，默认为true
         */
        Beta.canAutoDownloadPatch = true;
        /**
         * 设置是否自动合成补丁，默认为true
         */
        Beta.canAutoPatch = true;
        /**
         * 设置是否提示用户重启，默认为false
         */
        Beta.canNotifyUserRestart = true;
        /**
         * 补丁回调接口
         */
        Beta.betaPatchListener = new BetaPatchListener() {
            @Override
            public void onPatchReceived(String patchFile) {
                Toast.makeText(getApplication(), "补丁下载地址" + patchFile, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadReceived(long savedLength, long totalLength) {
                Toast.makeText(getApplication(),
                        String.format(Locale.getDefault(), "%s %d%%",
                                Beta.strNotificationDownloading,
                                (int) (totalLength == 0 ? 0 : savedLength * 100 / totalLength)),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadSuccess(String msg) {
                Toast.makeText(getApplication(), "补丁下载成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadFailure(String msg) {
                Toast.makeText(getApplication(), "补丁下载失败", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onApplySuccess(String msg) {
                Toast.makeText(getApplication(), "补丁应用成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onApplyFailure(String msg) {
                Toast.makeText(getApplication(), "补丁应用失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPatchRollback() {

            }
        };
        Bugly.init(getApplication(), APP_ID, false);
        //检测是否存在内存泄漏
//         LeakCanary.install(getApplication());
        Shadow.init(getApplication())
                .withApiHost(ServiceUrl.BASE_RELEASE_URL)
                //.withApiHost(ServiceUrl.BASE_DEBUG_URL)
                .withIcon(new FontAwesomeModule())
                .withIcon(new FontEcModule())
                .withLogger(new AndroidLogAdapter())
                .withJavascriptInterface("shadow")
                .withInterceptor(new GetCookieInterceptor())
                .withInterceptor(new AddCookieInterceptor())
                .withInterceptor(new LoggingInterceptor(true))
                .configure();
        //        DatabaseManager.getInstance().init(getApplication());
//                 Fragmentation.builder()
//                 // 设置 栈视图 模式为 悬浮球模式   SHAKE: 摇一摇唤出   NONE：隐藏
//                 .stackViewMode(Fragmentation.BUBBLE)
//                 // ture时，遇到异常："Can not perform this action after onSaveInstanceState!"时，会抛出
//                 // false时，不会抛出，会捕获，可以在handleException()里监听到
//                 .debug(BuildConfig.DEBUG)
//                 // 线上环境时，可能会遇到上述异常，此时debug=false，不会抛出该异常（避免crash），会捕获
//                 // 建议在回调处上传至我们的Crash检测服务器
//                 .handleException(new ExceptionHandler() {
//                     @Override
//                     public void onException(Exception e) {
//                         // 以Bugtags为例子: 手动把捕获到的 Exception 传到 Bugtags 后台。
//                         // Bugtags.sendException(e);
//                     }
//                 })
//                 .install();
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

        // 安装tinker
        // TinkerManager.installTinker(this); 替换成下面Bugly提供的方法
        Beta.installTinker(this);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }
}
